package com.leonzhangxf.server.register;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

/**
 * @author leonzhangxf
 */
public class ZkServerRegister implements ServerRegister {

    private final CuratorFramework client;

    public ZkServerRegister(String connectString) {
        client = CuratorFrameworkFactory.builder()
            .connectString(connectString)
            .retryPolicy(new ExponentialBackoffRetry(1000, 3, 10000))
            .namespace("program_1").build();

        client.start();
    }

    @Override
    public void register(String serviceId, String ip, int port) throws Exception {
        String serviceIdNode = String.format("/%s", serviceId);
        client.checkExists()
            .creatingParentsIfNeeded()
            .forPath(serviceIdNode);

        String nodeNode = String.format("%s/%s_%d", serviceIdNode, ip, port);
        if (null == client.checkExists().forPath(nodeNode)) {
            client.create().creatingParentsIfNeeded()
                .withMode(CreateMode.EPHEMERAL)
                .forPath(nodeNode);
        }
    }
}
